<!--
 * @Description: 新建/编辑群聊二维码
 * @Author: py
 * @Date: 2025-01-17
-->
<script setup lang="ts">
import type { FormInstance } from 'element-plus'

import { useQrcodeTypeDict, qrcodeListApi, qrcodeUpdateApi } from '@fl/api/advertising-api'
import FlUpload from '@fl/components/fl-upload.vue'
import { SubmitBtn } from '@fl/components'

interface QrcodeRow {
    id: number;
    chatType: number;
    chatName: string;
    chatImage: string;
    chatBgPic: string;
    activeCount: string;
    remark: string;
    isDeleted: number;
    [key: string]:  any
}

const props = withDefaults(defineProps<{
    data?: any
}>(), {
    data: () => {},
})

const emits = defineEmits(['success'])

const { data: rowData } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number | string>('id', { required: true })
const isEditMode = computed(() => {
    return !!id.value
})
const dialogTitle = computed(() => isEditMode.value ? '编辑' : '新建')

const formRef = ref()
// type ImageItem = {
//     name: string
//     url: string
// }
const initialState = {
    id: undefined,
    activeCount: '',
    qunType: undefined,
    chatName: '',
    remark: '',
    // isDeleted: 0,
    chatImage: '',
    chatBgPic: '',
}
const formValues = ref({ ...initialState })

const listData = ref<QrcodeRow[]>([])
function getQrList() {
    const oParams = {
        pageNo: 1,
        pageSize: 10000,
    }
    qrcodeListApi(oParams).then((res) => {
        const { rows } = res
        listData.value = rows
    })
}
getQrList()

const validateType = (_rule: any, value: any, callback: any) => {
    if (value === null || value === undefined) {
        callback(new Error('请输入类型'))
    } else if (listData.value.some(item => item.chatType === value) && value !== rowData.value.chatType) {
        callback(new Error('已有此类型，请重新输入'))
    } else {
        callback()
    }
}
const rules = {
    chatName: [{ message: '请输入群聊名称', required: true, trigger: 'blur' }],
    qunType: [{ validator: validateType, trigger: 'blur' }],
    // isDeleted: [{ message: '请选择状态', required: true, trigger: 'change' }],
    chatImage: [{ message: '请上传群聊二维码', required: true, trigger: 'change' }],
}

// const codeTypeOptions = ref<any>([])
// const { data: typeRes, isLoading } = useQrcodeTypeDict(visible)

watchEffect(() => {
    // if (typeRes.value) {
        // codeTypeOptions.value = typeRes.value

        if (isEditMode.value && rowData.value) {
            const { chatType, chatBgPic } = rowData.value
            // let cType;
            // if (chatType) {
            //     const targetItem = codeTypeOptions.value.find(item => item.dictValue === String(chatType));
            //     cType = targetItem ? targetItem.dictValue : undefined;
            // }

            formValues.value = {
                ...rowData.value,
                qunType: chatType,
                chatBgPic: chatBgPic ?? '',
            }
        }
    // }
})

const isPending = ref(false)
// 提交
async function handleSubmit(formEl: FormInstance | undefined) {
    if (!formEl)
        return
    await formEl.validate(async (valid) => {
        if (valid) {
            isPending.value = true
            const {
                id,
                activeCount,
                qunType,
                chatName,
                remark,
                // isDeleted,
                chatImage,
                chatBgPic,
            } = formValues.value

            const oParams = {
                id,
                activeCount,
                chatType: qunType,
                chatName,
                remark,
                // isDeleted,
                chatImage,
                chatBgPic,
            }

            try {
                await qrcodeUpdateApi(oParams)
                if (isEditMode.value) {
                    ElMessage.success('编辑成功')
                }
                else {
                    ElMessage.success('新增成功')
                }

                visible.value = false
                emits('success')
            }
            catch (error) {
                console.error(error)
            }
            finally {
                isPending.value = false
            }
        }
    })
}

// 取消
function handleCancel() {
    visible.value = false
}

// 重置
function handleReset(formEl: FormInstance | undefined) {
    id.value = ''
    formValues.value = { ...initialState }
    if (!formEl)
        return
    // formRef.value.formInstance.resetFields()
    formEl.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="600"
                close-on-press-escape
                @cancel="handleCancel"
                @closed="handleReset(formRef)"
    >
        <el-form ref="formRef"
                 :model="formValues"
                 :rules="rules"
                 label-width="auto"
        >
            <el-form-item label="群聊名称"
                          prop="chatName"
            >
                <el-input v-model="formValues.chatName"
                          clearable
                />
            </el-form-item>

            <el-form-item label="类型"
                          prop="qunType"
                          required
            >
                <el-input-number v-model="formValues.qunType"
                                 class="input-num"
                                 :controls="false"
                                 :min="0"
                                 :precision="0"
                />

                <!-- <el-select v-model="formValues.quType"
                           placeholder=''
                           clearable
                >
                    <el-option v-for="typeItem in codeTypeOptions"
                               :key="typeItem.dictValue"
                               :label="typeItem.dictLabel"
                               :value="typeItem.dictValue"
                    />
                </el-select> -->
            </el-form-item>

            <el-form-item label="群聊活跃描述">
                <el-input v-model="formValues.activeCount"
                          clearable
                />
            </el-form-item>

            <el-form-item label="备注">
                <el-input v-model="formValues.remark"
                          type="textarea"
                />
            </el-form-item>

            <!-- <el-form-item label="状态"
                          prop="isDeleted"
            >
                <el-radio-group v-model="formValues.isDeleted">
                    <el-radio :value="0">
                        正常
                    </el-radio>

                    <el-radio :value="1">
                        废弃
                    </el-radio>
                </el-radio-group>
            </el-form-item> -->

            <el-form-item label="群聊二维码"
                          prop="chatImage"
            >
                <FlUpload v-model="formValues.chatImage"
                          accept=".png,.jpg,.jpeg"
                />
            </el-form-item>

            <el-form-item label="主题背景">
                <FlUpload v-model="formValues.chatBgPic"
                          accept=".png,.jpg,.jpeg"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="handleCancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="handleSubmit(formRef)"
                >
                    确定
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="less" scoped>
.input-num {
    width: 100%;

    :deep(.el-input__inner) {
        text-align: left;
    }
}
</style>
